import urllib
import urllib2
import json
import os
import win32api
import win32gui
import win32con
import time
import sys
from PIL import Image

BASE_URL = 'http://www.bing.com'
JSON_URL = 'http://www.bing.com/HPImageArchive.aspx'
RESOLUTION = [(1920, 1200), (1920, 1080), (1366, 768), (800, 600)]
MKT = ['en-us']


def choose_resolution():
    width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)
    for resolution in RESOLUTION:
        if resolution[0] == width and resolution[1] == height:
            return resolution
    return RESOLUTION[0]


def gen_get_query(date_offset=0, mkt=MKT[0]):
    get_query = {
        'format': 'js',
        'idx': date_offset,
        'n': 1,
        'mkt': mkt
    }
    get_query = urllib.urlencode(get_query)
    return get_query


def get_image(image_url, image_name):
    #to avoid the IOError
    dir_path = os.path.join(os.environ['APPDATA'], 'BingWallpaperDownloader')
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    image_name = os.path.join(dir_path, image_name)
    try:
        urllib.urlretrieve(image_url, image_name)
    except IOError, e:
        win32api.MessageBox(0, e.message, '', 0)
    return os.path.abspath(image_name)


def parse_json(json_url, resolution):
    try:
        json_data = urllib2.urlopen(json_url).read()
    except:
        os.sys.exit(-1)
    json_data = json.loads(json_data)
    json_data = json_data['images'][0]
    image_url = '%s%s_%dx%d.jpg' % (BASE_URL, json_data['urlbase'], resolution[0], resolution[1])
    image_name = json_data['startdate'] + '.jpg'
    return image_url, image_name


def set_background(image_path):
    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, 'Control Panel\\Desktop', 0, win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(key, 'WallpaperStyle', 0, win32con.REG_SZ, '2')
    win32api.RegSetValueEx(key, 'TileWallpaper', 0, win32con.REG_SZ, '0')
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, image_path, win32con.SPIF_SENDCHANGE)

def convert_to_bmp(image_path):
    image = Image.open(image_path)
    bmp_image_path = image_path[:image_path.rfind('.')] + '.bmp'
    image.save(bmp_image_path, 'bmp')
    os.remove(image_path)
    return bmp_image_path


def set_startup():
    file_path = os.path.abspath(sys.argv[0])
    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Run', 0,
                                win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(key, 'BingWallpaperDownloader', 0, win32con.REG_SZ, '"%s" -autorun' % file_path)


def main():
    if len(sys.argv) < 2 or sys.argv[1] != '-autorun':
        set_startup()
    while True:
        resolution = choose_resolution()
        json_query_url = JSON_URL + '?' + gen_get_query()
        image_url, image_name = parse_json(json_query_url, resolution)
        image_path = get_image(image_url, image_name)
        image_path = convert_to_bmp(image_path)
        set_background(image_path)
        time.sleep(3600)


if __name__ == '__main__':
    main()